package com.corpgovernment.organization.util;

import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;

import java.util.stream.Collectors;

/**
 * @author ：llw
 * @date ：Created in 2020/12/9 11:48
 * @description：
 * @modified By：
 * @version: $
 */
public class ValidUtils {

    /**
     * 从BindingResult中读取错误信息
     *
     * @param bindingResult
     * @return
     */
    public static String getErrorStr(BindingResult bindingResult) {
        if (bindingResult == null || !bindingResult.hasErrors()) {
            return null;
        }

        if (CollectionUtils.isNotEmpty(bindingResult.getFieldErrors())) {
            return bindingResult.getFieldErrors().stream().map(fe -> String.format("%s -> %s", fe.getField(), fe.getDefaultMessage())).collect(Collectors.joining("，"));
        } else {
            return bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("，"));
        }
    }
}
